from flask import Flask
from flask_restful import Api, Resource, fields, marshal_with

app = Flask(__name__)
api = Api(app)


class User:
    def __init__(self, uname):
        self.uname = uname

    def __repr__(self):
        return f'<User uname:{self.uname}>'


class NewsType:
    def __init__(self, _type):
        self._type = _type

    def __repr__(self):
        return f'<User type:{self._type}>'


class News:
    def __init__(self, code, msg):
        self.code = code
        self.msg = msg
        self.user = None
        self._type = []

    def __repr__(self):
        return f'<News code:{self.code} msg:{self.msg} user:{self.user} type:{self._type}>'


def create_data():
    user = User('尚学堂')
    _type1 = NewsType('IT')
    _type2 = NewsType('Python')
    news = News(200, 'Python又双叕更新了！')
    news.user = user
    news._type.append(_type1)
    news._type.append(_type2)

    return news


class NewsView(Resource):
    resouce_fields = {
        'code': fields.Integer,
        'msg': fields.String,
        'user': fields.Nested({
            'uname': fields.String
        }),
        '_type': fields.List(fields.Nested({
            '_type': fields.String
        }))
    }

    @marshal_with(resouce_fields)
    def get(self):
        news = create_data()
        return news


api.add_resource(NewsView, '/news/')

if __name__ == '__main__':
    app.run(debug=True)


